import React, { useState, useEffect } from 'react';
import { Typography, Tabs, Table, Tag, Button, Space, message, Spin } from 'antd';
import { Link } from 'react-router-dom';
import { getOrders, Order, OrderQueryParams } from '../services/order.service';
import { formatDate } from '../utils/time';

const { Title } = Typography;
const { TabPane } = Tabs;

const OrdersPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [activeTab, setActiveTab] = useState('all');

  useEffect(() => {
    fetchOrders();
  }, [activeTab, page, pageSize]);

  const fetchOrders = async () => {
    try {
      setLoading(true);
      const params: OrderQueryParams = {
        page,
        pageSize,
      };
      
      if (activeTab !== 'all') {
        params.status = activeTab as 'pending' | 'paid' | 'cancelled' | 'completed';
      }
      
      const response = await getOrders(params);
      setOrders(response.orders);
      setTotal(response.total);
    } catch (error) {
      console.error('Failed to fetch orders:', error);
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setPage(1);
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'pending':
        return <Tag color="blue">待支付</Tag>;
      case 'paid':
        return <Tag color="green">已支付</Tag>;
      case 'cancelled':
        return <Tag color="red">已取消</Tag>;
      case 'completed':
        return <Tag color="purple">已完成</Tag>;
      default:
        return null;
    }
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
      render: (text: string, record: Order) => (
        <Link to={`/orders/${record.id}`}>{text}</Link>
      ),
    },
    {
      title: '商品',
      dataIndex: 'items',
      key: 'items',
      render: (items: any[]) => (
        <span>
          {items.map(item => item.product.name).join(', ')}
        </span>
      ),
    },
    {
      title: '金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => formatDate(date),
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: Order) => (
        <Space size="small">
          <Link to={`/orders/${record.id}`}>
            <Button type="link" size="small">查看详情</Button>
          </Link>
          {record.status === 'pending' && (
            <Link to={`/orders/${record.id}/pay`}>
              <Button type="primary" size="small">去支付</Button>
            </Link>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="orders-page">
      <Title level={2}>我的订单</Title>
      
      <Tabs activeKey={activeTab} onChange={handleTabChange}>
        <TabPane tab="全部订单" key="all" />
        <TabPane tab="待支付" key="pending" />
        <TabPane tab="已支付" key="paid" />
        <TabPane tab="已完成" key="completed" />
        <TabPane tab="已取消" key="cancelled" />
      </Tabs>
      
      {loading ? (
        <div style={{ textAlign: 'center', padding: '50px 0' }}>
          <Spin size="large" />
        </div>
      ) : (
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          pagination={{
            current: page,
            pageSize: pageSize,
            total: total,
            onChange: (page, pageSize) => {
              setPage(page);
              if (pageSize) setPageSize(pageSize);
            },
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条订单`,
          }}
        />
      )}
    </div>
  );
};

export default OrdersPage; 